package com.fs.video.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.video.common.sysconst.SystemConst;
import com.fs.video.common.utils.FileUploadUtil;
import com.fs.video.common.utils.IdWorkerUtil;
import com.fs.video.mapper.VideosMapper;
import com.fs.video.pojo.Videos;
import com.fs.video.service.VideosService;
import com.fs.video.vo.VideosVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

@Service
public class VideosServiceImpl implements VideosService {
    @Autowired
    private VideosMapper videosMapper;


    @Override
    public String upload(String userId, MultipartFile video) {
        //d:/zk-video/1231231312/video
        String savePath = SystemConst.SAVE_ROOT_PATH+userId+"/video/";
        String savePathDb = "/"+userId+"/video/";
        //1.判断文件保存目录是否存在
        FileUploadUtil.createPath(savePath);
        //2.如果存在, 保存文件
        String oFilename = video.getOriginalFilename();
        savePath += oFilename;  //savePath = savePath+oFilename;
        try {
            video.transferTo(new File(savePath));
            //3.返回文件保存路径
            savePathDb += oFilename;
            return savePathDb;
        } catch (IOException e) {
           throw new RuntimeException(e);
        }
    }


    @Override
    @Transactional
    public void save(Videos videos) {
        videos.setId(String.valueOf(IdWorkerUtil.getNextId()));
        videos.setLikeCounts(0L);
        videos.setStatus(SystemConst.VIDEO_NOMAL_STATUS);
        videos.setCreateTime(new Date());
       videosMapper.insert(videos);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public IPage<VideosVO> selectByPage(Integer pageIndex, Integer pageSize) {
        IPage<VideosVO> pages = new Page<>(pageIndex,pageSize);
        pages.setRecords(videosMapper.queryByPage(pages));
        return pages;
    }
}
